Good Programming Practices

Whenever we develop programs, the correctness of the program (whether it produces the "right" results) is a very important concern, but it is not the only concern. Other important factors include efficiency and programming style. Efficiency refers to whether the program runs in a reasonable amount of time and uses a reasonable amount of memory. These guidelines represent some common good practices in programming.

Comments are an important and effective way of making our programs easier to read and understand (as well as debug). Comments are meant for humans to read; in fact, Matlab ignores all comments when it executes code. Comments in Matlab begin with a percent sign ( % ) and continue to the end of the line. Use comments in the code to document what your code does or provide an external document that describes the purpose, inputs, and outputs, of your program.

Here's a program that illustrates these guidelines.

     % Program that converts height in feet and inches to meters
     % Author(s): Becky Badger, Bucky Badger
     % Version: 1.0.01  
     % Date: October 1, 2006
    
     % Input the data (may use input command here or read from file)
     feet = inputHeight(1) ;      % may input from user or file
     inch = inputHeight(2) ;

     % Calculate height in inches and meters, uses 2.54 cm/in
     MPI = 0.0254 ;
     heightIn = feet*12 + inch ;  
     heightM  = heightIn * MPI ;  

     % Output the height to the user in an easy to read form
     disp( ['The height ', num2str(feet), 'feet ', num2str(inch), ...
            'inches = ', num2str(heightM), ' meters']);